// 将base64转换为文件
function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);
  while(n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

// 转base64文件
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
// 压缩图片
export function compressImage(file, config) {
  return new Promise((resolve, reject) => {
    // 压缩图片需要的一些元素和对象
    let reader = new FileReader();
    // 创建一个img对象
    let img = new Image()
    config = config || {}
    reader.readAsDataURL(file)
    // 文件base64化，以便获知图片原始尺寸
    reader.onload = function (e) {
      img.src = e.target.result
    }

    // base64地址图片加载完毕后执行
    img.onload = function () {
      // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
      let canvas = document.createElement('canvas')
      let context = canvas.getContext('2d')

      // 图片原始尺寸
      let originWidth = this.width
      let originHeight = this.height

      // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
      let maxWidth = config.width || 300
      let maxHeight = config.height || 300
      if (originWidth > maxWidth || originHeight > maxHeight) {
        // 目标尺寸
        let targetWidth = originWidth
        let targetHeight = originHeight
        // 图片尺寸超过300x300的限制
        let fileNew = file;
        if (originWidth > maxWidth || originHeight > maxHeight) {
          if (originWidth / originHeight > maxWidth / maxHeight) {
            // 更宽，按照宽度限定尺寸
            targetWidth = maxWidth
            targetHeight = Math.round(maxWidth * (originHeight / originWidth))
          } else {
            targetHeight = maxHeight
            targetWidth = Math.round(maxHeight * (originWidth / originHeight))
          }

          // canvas对图片进行缩放
          canvas.width = targetWidth
          canvas.height = targetHeight
          // 清除画布
          context.clearRect(0, 0, targetWidth, targetHeight)
          // 图片压缩
          context.drawImage(img, 0, 0, targetWidth, targetHeight)
          // base64 格式
          let base64 = canvas.toDataURL('image/jpeg', 0.92)
          fileNew = dataURLtoFile(base64, file.name)
          fileNew.uid = file.uid
        }
        resolve(fileNew)
      }
    }
  })
}
